package br.com.cast.UseCaseProdutos.services;

import java.util.Iterator;

import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import br.com.cast.UseCaseProdutos.excecoes.NotaFiscalJaCadastrada;
import br.com.cast.UseCaseProdutos.models.NotaFiscal;
import br.com.cast.UseCaseProdutos.persistencia.NotaFiscalDAO;

/**
 * Serviço utilizado nas funcionalidades do Manter Nota Fiscal
 * 
 * @author matheus.mesquita
 * 
 */
@Component
public class NotaFiscalService implements INotaFiscalService {

	private static final long serialVersionUID = 1L;

	@Autowired
	private NotaFiscalDAO notaFiscalDAO;

	@Transactional
	@Override
	public void salvar(NotaFiscal notaFiscal) {
		if (notaFiscalDAO.notaFiscalJaCadastrada(notaFiscal))
			throw new NotaFiscalJaCadastrada();
		else {
			if (notaFiscal.getId() == null) {
				notaFiscalDAO.salvar(notaFiscal);
			} else {
				notaFiscalDAO.alterar(notaFiscal);
			}
		}
	}

	@Transactional
	@Override
	public void excluir(NotaFiscal notaFiscal) {
		notaFiscalDAO.excluir(notaFiscal);
	}

	@Override
	public void detach() {
	}

	@Override
	public Iterator<? extends NotaFiscal> iterator(long inicio, long count) {
		return notaFiscalDAO.consultaPaginada(inicio, count);
	}

	@Override
	public long size() {
		return notaFiscalDAO.total(NotaFiscal.class);
	}

	@Override
	public IModel<NotaFiscal> model(NotaFiscal notaFiscal) {
		return new CompoundPropertyModel<>(notaFiscal);
	}

}
